import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { message } from 'antd';
import { DATA_ENTRY, AdvancedSearch, codeType, NestedTableC } from '../../../comps';
import moment from 'moment';
import config from '../../../comps/business/tradingMarket/config';
import uuid from 'es6-uuid';

@Form.create()
class ConvertibleBondList extends PureComponent {
  state = {
    dataSource: [], // 表格数据
    columns: [], // 表头
    pageInfo: {}, // 页码信息
    currentPage: 1, // 当前页
    numInPage: 20, // 每页条数
    search: undefined, // 搜索表单值
    sortedInfo: null, // 排序对象
    isReset: false, // 重置标志位
    dateObj: undefined, // 默认日期
  };

  componentDidMount() {
    if (sessionStorage.getItem('workPlaceConvertible') || sessionStorage.getItem('workPlaceConvertible1')) {
      // 首次进入页面从工作台获取时间信息
      const dateObj = JSON.parse(sessionStorage.getItem('workPlaceConvertible') || sessionStorage.getItem('workPlaceConvertible1'));
      sessionStorage.setItem('workPlaceConvertible1', JSON.stringify(dateObj)); // 页面刷新重置默认值需要
      this.setState(
        {
          dateObj,
          search: { startDate: moment(dateObj.startTime), endDate: moment(dateObj.endTime) },
        },
        () => {
          // 初始化页面数据
          this.getTableData();
          sessionStorage.removeItem('workPlaceConvertible'); // 清空
        },
      );
    } else {
      // 初始化页面数据
      this.getTableData();
    }
  }

  UNSAFE_componentWillReceiveProps() {
    if (sessionStorage.getItem('workPlaceConvertible')) {
      // 从主页反复进入 总是取主页的日期
      const dateObj = JSON.parse(sessionStorage.getItem('workPlaceConvertible'));
      // 默认工作台入参
      this.state.RANGEDATE && this.state.RANGEDATE.setDate([moment(dateObj.startTime), moment(dateObj.endTime)]);
      this.state.SECURITIESCODE && this.state.SECURITIESCODE.setSelect();
      this.setState(
        {
          dateObj,
          search: { startDate: moment(dateObj.startTime), endDate: moment(dateObj.endTime) },
        },
        () => {
          sessionStorage.setItem('workPlaceConvertible1', JSON.stringify(dateObj)); // 页面刷新重置默认值需要
          this.getTableData();
          sessionStorage.removeItem('workPlaceConvertible'); // 清空
        },
      );
    }
  }

  // 获取列表数据
  getTableData = () => {
    const { dispatch } = this.props;
    const { currentPage, numInPage, search, isReset } = this.state;
    if (isReset) {
      message.warning('已重置查询条件，请重新查询');
      return;
    }
    const sortedInfo = this.state.sortedInfo ? this.state.sortedInfo : {};
    if (sortedInfo && sortedInfo.column && sortedInfo.column.sorter !== true) return; // 非排序字段不进行请求
    let params = {};
    if (search) {
      params = {
        tradingCode: search.tradingCode,
        exchangeCode: search.exchangeCode,
        startDate: search.startDate ? moment(search.startDate).format('YYYY-MM-DD') : undefined,
        endDate: search.endDate ? moment(search.endDate).format('YYYY-MM-DD') : undefined,
      };
    }
    dispatch({
      type: 'convertibleBondListM/getTableData',
      payload: {
        sortItem: sortedInfo.field || undefined,
        sortType: sortedInfo.order || undefined, // 升序-ascend 、降序-descend
        currentPage,
        numInPage,
        ...params,
      },
      callback: (res) => {
        if (res) {
          res.dataSource &&
            res.dataSource.map((item, key) => {
              item.key = key;
              if (item.nestedConfig) {
                item.nestedConfig.dataSource &&
                  item.nestedConfig.dataSource.map((child) => {
                    child.key = uuid(6);
                    child.leftValueTotal = parseFloat((child.leftValueTotal || 0) / 10000); // 展示万元
                  });
                item.nestedConfig.columns &&
                  item.nestedConfig.columns.map((child) => {
                    child.width = '300px';
                    if (child.key == 'leftValueTotal') {
                      child.type = 'money';
                    }
                  });
              }
            });
          this.setState({
            dataSource: res.dataSource || [],
            columns: res.columns || [],
            pageInfo: res.pageInfo || {},
          });
        } else {
          this.setState({
            dataSource: [],
            columns: [],
            pageInfo: {},
          });
        }
      },
    });
  };

  // 到期表格靠右
  setColumns = (columns) => {
    let { sortedInfo } = this.state;
    const arr = columns;
    sortedInfo = sortedInfo || {};
    if (arr && arr.length) {
      arr.map((item) => {
        if (item.key == 'beginDate' || item.key == 'fundreceiveDate' || item.key == 'convendDate') {
          item.sorter = true;
          item.sortOrder = sortedInfo.columnKey === item.key && sortedInfo.order;
        }
        if (item.key == 'exchangeCode') {
          item.render = (text, record) => {
            const findvalue = config.filter((item) => {
              return item.value == text;
            });
            if (findvalue && findvalue.length > 0) {
              return findvalue[0].title;
            } else {
              return '--';
            }
          };
        }
        if (item.key == 'execprice') {
          item.type = 'money';
        }
      });
    }
    return arr;
  };

  // 表格页码排序改变调用
  handleTableChange = (pagination, filter, sorter) => {
    const { current, pageSize } = pagination;
    this.setState(
      {
        currentPage: current,
        numInPage: pageSize,
        sortedInfo: sorter, // 无法直接使用sorter里的变量赋值，否则排序状态有问题，需要配合使用sortOrder
      },
      () => {
        this.getTableData();
      },
    );
  };

  render() {
    const { columns, dataSource, pageInfo, dateObj } = this.state;
    const newColumns = this.setColumns(columns);
    const searchProps = {
      dataSource: [
        {
          dataIndex: ['startDate', 'endDate'],
          title: '行权日',
          type: DATA_ENTRY.RANGEDATE,
          initialValue: dateObj ? [moment(dateObj.startTime), moment(dateObj.endTime)] : undefined,
          onRef: (ref) => this.setState({ RANGEDATE: ref }),
          disableFuture: false,
        },
        {
          dataIndex: 'tradingCode',
          title: '证券代码',
          type: DATA_ENTRY.SECURITIESCODE,
          codeType: codeType.zq,
          onRef: (ref) => this.setState({ SECURITIESCODE: ref }),
        },
      ],
      onQuery: (e) => {
        this.setState(
          {
            currentPage: 1,
            search: e,
            isReset: false,
          },
          () => {
            this.getTableData();
          },
        );
      },
      onClear: () => {
        // 点击重置按钮
        this.setState({
          search: undefined,
          isReset: true, // 重置标志位
          currentPage: 1,
          pageSize: 20,
          sortedInfo: null,
        });
      },
    };
    return (
      <div>
        <div style={{ marginBottom: '10px' }}>
          <AdvancedSearch {...searchProps} />
        </div>
        <div>
          <NestedTableC
            columns={newColumns}
            dataSource={dataSource}
            rowKey='key'
            fixedChild={true}
            loading={this.props.loading === true}
            commonHeader={false}
            current={pageInfo?.currentPage}
            total={pageInfo?.total}
            pageSize={pageInfo?.numInPage}
            onChange={this.handleTableChange}
          />
        </div>
      </div>
    );
  }
}
export default connect(({ convertibleBondListM, loading }) => ({ convertibleBondListM, loading: loading.effects['convertibleBondListM/getTableData'] }))(ConvertibleBondList);
